import url from "../baseUrl.js"

import {
	tip
} from "../../static/js/public.js"
import {
	isImage
} from "../../static/js/public.js"

export function imgSet(s, imgData, fileData) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			...imgData,
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFiles;
				for (let temp of tempFilePaths) {
					uni.uploadFile({
						url: url.baseUrl + s,
						method: 'POST',
						file: temp,
						filePath: temp.path,
						name: 'file',
						header: {},
						formData: {
							token: uni.getStorageSync('token'),
							avatarfile: temp,
							// file:temp,
							...fileData
						},
						success: (res) => {
							var data = JSON.parse(res.data);
							resolve(data)
						},
						fail: error => {
							tip("上传失败")
							reject(error)
						},
					});
				}

			}
		})
	})
}


export function imgSets(s, imgData, fileData) {
	// console.log(imgData)
	return new Promise((resolve, reject) => {

		uni.chooseImage({
			...imgData,
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				let imgs = tempFilePaths.map((value, index) => {
					return {
						name: 'file' + index,
						uri: value,
					}
				})
				uni.uploadFile({
					url: url.baseUrl + s,
					method: 'POST',
					files: imgs,
					// name: 'file',
					formData: {
						token: uni.getStorageSync('token'),
					},
					success: (res) => {
						console.log('1111111111111',res)
						resolve(JSON.parse(res.data))
					},
					fail: error => {
						tip("上传失败")
						reject(error)
					},
				});

			}
		})
	})
}

export function FileImgSave(url) {



	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '下载中',
			mask: true,
		})

		// #ifdef APP-PLUS

		if (isImage(url)) {
			uni.saveImageToPhotosAlbum({
				filePath: url,
				success: function() {
					self.tip("保存相册成功")
				}
			});
			uni.hideLoading()
		} else {
			uni.downloadFile({
				url: url,
				success: (res) => {
					if (res.statusCode === 200) {
						console.log('下载成功');
					}
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						success: function(red) {
							uni.hideLoading()
							tip(`下载成功,路径为${red.savedFilePath}`);
							resolve(red)
						},
						fail(err) {
							tip(`下载失败`);
							uni.hideLoading()
							reject(err)
						}
					});
				},
				fail(err) {
					tip(`下载失败`);
					uni.hideLoading()
				}
			});
		}

		// #endif

		// #ifdef H5


		window.open(url)
		uni.hideLoading()
		// #endif

	})
}

export function setFile(s, temp, fileData = {}) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: url.baseUrl + s,
			method: 'POST',
			file: temp,
			filePath: temp,
			name: 'file',
			header: {},
			formData: {
				token: uni.getStorageSync('token'),
				...fileData
			},
			success: (res) => {
				var data = JSON.parse(res.data);
				resolve(data)
			},
			fail: error => {
				tip("上传失败")
				reject(error)
			},
		});
	})

}
